from . import atom
import api.models
import docutils.core
import docutils.writers
import simplejson
from google.appengine.api import users
from google.appengine.ext import webapp
import cgi
import datetime
import sys
import traceback
import urllib
import logging


class UserFeed(atom.Feed):

    url = "http://moi-online.appspot.com"

    def get_object(self, params):
        """Return the User object for the specified feed."""
        email = urllib.unquote(params[0])
        user = users.User(email=email)
        # Verify email address is even known.
        if not api.models.DataObject.all().filter('user =', user).count(1):
            raise LookupError("%s is not a valid account" % email)
        return user

    def feed_id(self, obj):
        """URL to the feed."""
        return "%s/snippet/%s/" % (self.url, obj.email())

    def feed_title(self, obj):
        """Title of the feed."""
        return "Weekly snippets for %s" % obj.nickname()

    def feed_authors(self, obj):
        """Who the feed represents."""
        return [{'name': obj.nickname()}]

    def feed_updated(self, obj):
        """The start date for the newest snippet."""
        snippets = self.items(obj)
        if len(snippets) < 1:
            return datetime.datetime.now()
        else:
            return snippets[0].updated

    def items(self, obj):
        """Return the latest snippets."""
        today = datetime.date.today()
        prev_monday = today - datetime.timedelta(today.weekday())
        all_snippets = api.models.DataObject.all().filter('user =', obj)
        snippets = all_snippets.filter('updated < ', prev_monday)
        found = []
        for snippet in snippets:
            post = simplejson.loads(snippet.json)
            if 'summary' in post:
                found.append(snippet)
                if (len(found)) == 5:
                    break
        return found

    def item_id(self, item):
        """URL to a specific snippet (which is invalid)."""
        email = item.user.email()
        return "%s/snippet/%s/%s" % (self.url, email, item.date_str())

    def item_title(self, item):
        """Title for a snippet."""
        post = simplejson.loads(item.json)
        return "Snippet for the week of %s" % post['date']

    def item_updated(self, item):
        """Start date for a snippet."""
        post = simplejson.loads(item.json)
        return datetime.datetime(*map(int, post['date'].split('-')))

    def item_content(self, item):
        """Summary of a snippet."""
        data = simplejson.loads(item.json)
        settings = {'input_encoding': 'utf8', 'output_encoding': 'utf8',
                    '_disable_config': True}
        writer = docutils.writers.get_writer_class("html")()
        html = docutils.core.publish_parts(data['summary'], writer=writer,
                                            settings_overrides=settings)
        html_body = html['html_body']
        return {'type': 'html'}, html_body


class FeedView(webapp.RequestHandler):

    def get(self, email):
        try:
            feed = UserFeed(None, None).get_feed(email)
        except LookupError, exc:
            self.error(404)
            logging.error(traceback.format_exc(sys.exc_info()[2]))
            return
        self.response.headers['Content-Type'] = feed.mime_type
        encoding = "utf-8"
        self.response.headers['Content-Encoding'] = encoding
        feed.write(self.response.out, encoding)
